<template>
  <div class="page-upload-wrap">
    <div class="desc-box">
      <div class="desc-content">
        <el-alert
          v-if="clientSettings && clientSettings.desc"
          :title="clientSettings.desc"
          type="warning"
          :closable="false"
        />
      </div>
      <el-button @click="toRecords">上传记录</el-button>
    </div>
    <div class="excel-download-box">
      <div class="excel-box">
        <el-button type="primary" @click="batchImport">批量导入</el-button>
        <p>（请下载右侧excel模板文件，录入内容后再上传，文件大小限制在500k以下。）</p>
      </div>
      <div class="template-files" v-if="clientSettings && clientSettings.templates">
        <a
          v-for="template in clientSettings.templates"
          :key="template.file_url"
          @click="viewTemplateFile(template)"
          >{{ template.name }}</a
        >
      </div>
    </div>
    <div class="table-wrap">
      <el-card style="height: 100%">
        <div style="text-align: right">
          <el-button type="success" link @click="insertFile">+新增文件</el-button>
        </div>
        <div style="height: calc(100% - 70px)">
          <el-table :data="tableData" border height="100%" style="width: 100%" align="center">
            <el-table-column prop="fileName" label="文件名" width="250">
              <template #default="scope">
                <TextInput v-model="scope.row.fileName" :max="20"></TextInput>
              </template>
            </el-table-column>
            <el-table-column prop="fileDesc" label="功能" width="400">
              <template #default="scope">
                <TextInput v-model="scope.row.fileDesc" :max="100"></TextInput>
              </template>
            </el-table-column>
            <el-table-column prop="relatedUrl" label="下载网址">
              <template #default="scope">
                <TextInput v-model="scope.row.relatedUrl"></TextInput>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="上传文件" width="250">
              <template #header>
                <div style="display: flex; align-items: center">
                  <span>上传文件</span>
                  <el-tooltip
                    v-if="clientSettings && clientSettings.fileSizeLimit"
                    :content="`文件大小限制在${clientSettings.fileSizeLimit.min.value}${clientSettings.fileSizeLimit.min.unit} - ${clientSettings.fileSizeLimit.max.value}${clientSettings.fileSizeLimit.max.unit}`"
                    placement="top"
                  >
                    <el-icon style="margin-left: 5px; cursor: pointer"><WarningFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <template #default="scope">
                <el-button
                  v-if="!scope.row.filename"
                  link
                  type="primary"
                  size="small"
                  @click.prevent="uploadItemFile(scope)"
                >
                  上传文件
                </el-button>
                <div class="file-box" v-else>
                  <div class="file-name">
                    <el-icon><DocumentRemove></DocumentRemove> </el-icon>
                    <el-tooltip :content="scope.row.filename" placement="top">
                      <span>{{ scope.row.filename }}</span>
                    </el-tooltip>
                  </div>
                  <el-icon class="remove-btn" @click="removeRowFile(scope)"
                    ><CircleCloseFilled></CircleCloseFilled>
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="120">
              <template #default="scope">
                <el-button link type="danger" size="small" @click.prevent="deleteRow(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table-footer">
          <el-button @click="clearTable">清空</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </el-card>
    </div>
    <div class="footer" v-if="clientSettings && clientSettings.links">
      <a
        v-for="item in clientSettings.links"
        :key="item.url"
        :href="item.url"
        :target="item.open_in_this ? '' : '_blank'"
        >{{ item.name }}</a
      >
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/store/modules/app'
import TextInput from '@/components/TextInput/index.vue'
import { ElMessage } from 'element-plus'
import { CircleCloseFilled, DocumentRemove, WarningFilled } from '@element-plus/icons-vue'
import { read, utils } from 'xlsx'
import { batchFileApi } from '@/api/files'
import { useLoading } from '@/hooks/loading'
const { isLoading, startLoading, endLoading } = useLoading()

const router = useRouter()
const appStore = useAppStore()

const clientSettings = computed(() => appStore.getClientSettings)
const userinfo = computed(() => appStore.getUserinfo)

// 跳转查看记录
const toRecords = () => {
  router.push({
    name: 'Records'
  })
}

// 查看模板文件
const viewTemplateFile = (item) => {
  window.open(item.url, '_blank')
}

const tableData = ref([])
// 批量导入
const batchImport = () => {
  const file_input = document.createElement('input')
  file_input.type = 'file'
  file_input.accept =
    '.csv,.xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  file_input.addEventListener('change', (e) => {
    if (e.target.files.length) {
      const reader = new FileReader()
      const file = e.target.files[0]
      if (file.size / 1024 > 500) {
        ElMessage.error('所选文件大于500kb!')
        return
      }
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = read(data, { type: 'array' })
          const worksheet = workbook.Sheets[workbook.SheetNames[0]]
          const excelData = utils.sheet_to_json(worksheet, { header: 1 })
          if (excelData && excelData.length && excelData[0]) {
            const headerData = excelData[0]
            const columns = [
              ['文件名', 'fileName', 0],
              ['功能', 'fileDesc', 0],
              ['下载网址', 'relatedUrl', 0]
            ]
            columns.forEach((item) => {
              const index = headerData.findIndex((val) => val === item[0])
              if (index < 0) {
                throw new Error(`内容缺少${item}列!`)
              }
              item[2] = index
            })
            // 数据正常
            tableData.value = tableData.value.concat(
              excelData
                .filter((_, i) => i !== 0)
                .map((item) => {
                  let obj = {}
                  columns.forEach((val) => {
                    obj[val[1]] = item[val[2]]
                  })
                  return obj
                })
            )
          } else {
            throw new Error('文件内容不正确！')
          }
        } catch (err) {
          console.log(err)
          ElMessage.error(err.message)
        }
      }
      reader.readAsArrayBuffer(file)
    }
  })
  file_input.click()
}
// 新增单条文件
const insertFile = () => {
  tableData.value.push({})
}
// 上传文件
const uploadItemFile = (scope) => {
  const file_input = document.createElement('input')
  file_input.type = 'file'
  file_input.accept = '.schdoc'
  file_input.addEventListener('change', (e) => {
    if (e.target.files.length) {
      try {
        const file = e.target.files[0]
        const { min, max } = clientSettings.value.fileSizeLimit || {}
        const getBytes = (v, u) => {
          if (u === 'KB') return v * 1024
          if (u === 'MB') return v * 1024 * 1024
        }
        if (min && max) {
          const minBytes = getBytes(min.value, min.unit)
          const maxBytes = getBytes(max.value, max.unit)
          if (file.size < minBytes) {
            throw new Error(`所选文件大小不得小于${min.value}${min.unit}`)
          } else if (file.size > maxBytes) {
            throw new Error(`所选文件大小不得大于${max.value}${max.unit}`)
          }
        }
        scope.row.file = file
        scope.row.filename = file.name
      } catch (err) {
        console.log(err)
        ElMessage.error(err.message)
      }
    }
  })
  file_input.click()
}
// 移除文件
const removeRowFile = (scope) => {
  delete scope.row.filename
  delete scope.row.formData
}

// 清空表格
const clearTable = () => {
  tableData.value = []
}

// 删除行
const deleteRow = (index) => {
  tableData.value.splice(index, 1)
}

// 提交表格
const submitForm = async () => {
  if (userinfo.status === 3) {
    ElMessage.error('该用户已被禁止上传！')
    return
  }
  startLoading()
  try {
    if (!tableData.value.length) {
      throw new Error('请至少上传一个文件！')
    }
    const formData = new FormData()
    tableData.value.forEach((item) => {
      if (!item.fileName.trim()) {
        throw new Error('文件名为必填项！')
      }
      if (!item.relatedUrl.trim()) {
        throw new Error('下载网址为必填项！')
      }
      if (!item.filename) {
        throw new Error('上传文件不能为空！')
      }

      formData.append('fileName', item.fileName)
      formData.append('relatedUrl', item.relatedUrl)
      formData.append('fileDesc', item.fileDesc)
      formData.append('file', item.file, item.filename)
    })

    const res = await batchFileApi(formData)
    if (res && res.code) {
      ElMessage.success('上传成功！')
      tableData.value = []
    }
  } catch (error) {
    console.log(error)
    ElMessage.error(error.message)
  }
  endLoading()
}
</script>

<style scoped lang="less">
.page-upload-wrap {
  padding: 30px;
  height: 100%;
  position: relative;
  box-sizing: border-box;
  .desc-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .desc-content {
      flex: 1;
      margin-right: 30px;
    }
  }
  .excel-download-box {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .excel-box {
      display: flex;
      align-items: center;
      p {
        margin: 0;
        margin-left: 10px;
        color: #999;
        font-size: 12px;
      }
    }
    .template-files {
      a {
        cursor: pointer;
        margin-left: 15px;
        color: var(--el-color-primary);
        text-decoration: none;
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }

  .table-wrap {
    margin-top: 10px;
    height: calc(100% - 120px);
    position: relative;
    .table-footer {
      position: absolute;
      right: 10px;
      bottom: 10px;
    }
    .file-box {
      display: flex;
      align-items: center;
      justify-content: space-around;
      .file-name {
        display: flex;
        align-items: center;
        span {
          font-size: 12px;
          width: 150px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
      .remove-btn {
        cursor: pointer;
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }
  }

  .footer {
    position: absolute;
    right: 30px;
    bottom: 20px;
    a {
      cursor: pointer;
      margin-left: 15px;
      color: #999;
      font-size: 12px;
      text-decoration: none;
      &:hover {
        color: #333;
      }
    }
  }
}

:deep(.el-card) {
  .el-card__body {
    padding: 10px !important;
    height: 100%;
    box-sizing: border-box;
  }
}
</style>
